<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class City extends Model
{
    protected $table = 'tn_dic_district';

    public function beforeLinkage()
    {
        $columns = ['id', 'name'];

        $data['provinces'] = $this->provinces($columns);
        $data['cities']    = $this->cities($data['provinces']->first(), $columns);
        $data['counties']  = $this->counties($data['cities']->first(), $columns);

        return $data;
    }

    public function provinces(array $columns = ['*'])
    {
        return $this->select($columns)->where(['level' => 1])->get();
    }

    public function cities($province, array $columns = ['*'])
    {
        return $this->select($columns)->where([
            'level' => 2,
            'upid' => $this->parseIdValue($province),
        ])->get();
    }

    public function counties($city, array $columns = ['*'])
    {
        return $this->select($columns)->where([
            'level' => 3,
            'upid' => $this->parseIdValue($city),
        ])->get();
    }

    public function parseIdValue($city)
    {
        if ($city instanceof City) {

            return $city->getKey();
        } elseif (is_numeric($city)) {

            return $city;
        }

        throw new \InvalidArgumentException('参数错误', 400);
    }
}
